import React, { useState } from 'react';
import {
  Box,
  TextField,
  Button,
  Typography,
  Alert,
  Paper,
  Grid,
  IconButton,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
} from '@mui/material';
import DeleteIcon from '@mui/icons-material/Delete';
import { Product, RateRecord, TimeLabel } from '../../types/product';
import { checkTimeConflicts } from '../../utils/calculations';

interface ProductEntryProps {
  onSubmit: (product: Product) => void;
}

const ProductEntry: React.FC<ProductEntryProps> = ({ onSubmit }) => {
  const [product, setProduct] = useState<Partial<Product>>({
    bank: '',
    name: '',
    netWorth: 1.0000,
    investments: [],
    historyRates: [],
  });

  const [error, setError] = useState<string>('');

  const handleProductChange = (field: keyof Product, value: any) => {
    setProduct((prev: Partial<Product>) => ({ ...prev, [field]: value }));
  };

  const handleAddRate = () => {
    const newRate: RateRecord = {
      id: Date.now().toString(),
      startDate: new Date(),
      endDate: new Date(),
      rate: 0,
      advertisedRate: 0,
      dailyProfit: 0,
      timeLabel: TimeLabel.OneMonth,
    };

    setProduct((prev: Partial<Product>) => ({
      ...prev,
      historyRates: [...(prev.historyRates || []), newRate],
    }));
  };

  const handleUpdateRate = (index: number, field: keyof RateRecord, value: any) => {
    setProduct((prev: Partial<Product>) => {
      const historyRates = [...(prev.historyRates || [])];
      historyRates[index] = {
        ...historyRates[index],
        [field]: field.includes('Date') ? new Date(value) : 
                field === 'timeLabel' ? value :
                Number(value),
      };
      return { ...prev, historyRates };
    });
  };

  const handleRemoveRate = (index: number) => {
    setProduct((prev: Partial<Product>) => ({
      ...prev,
      historyRates: (prev.historyRates || []).filter((_, i) => i !== index),
    }));
  };

  const handleSubmit = () => {
    if (!product.bank || !product.name || !product.historyRates?.length) {
      setError('请填写所有必填字段');
      return;
    }

    // 验证净值格式
    if (!product.netWorth || product.netWorth <= 0 || 
        String(product.netWorth).split('.')[1]?.length > 6) {
      setError('请输入正确的净值格式（最多4位小数）');
      return;
    }

    // 验证收益率记录
    for (const record of product.historyRates) {
      if (record.startDate >= record.endDate) {
        setError('收益率记录的开始日期必须早于结束日期');
        return;
      }
      if (record.advertisedRate < 0 || record.dailyProfit < 0) {
        setError('收益率不能为负数');
        return;
      }
    }

    const newProduct: Product = {
      ...product as Product,
      id: Date.now().toString(),
      createdAt: new Date(),
      updatedAt: new Date(),
    };

    try {
      onSubmit(newProduct);
    } catch (err) {
      setError('保存失败，请重试');
    }
  };

  const formatDateForInput = (date: Date | undefined): string => {
    if (!date) return '';
    return date instanceof Date 
      ? date.toISOString().split('T')[0]
      : new Date(date).toISOString().split('T')[0];
  };

  return (
    <Box component={Paper} p={3}>
      <Typography variant="h6" gutterBottom>
        添加理财产品
      </Typography>

      {error && (
        <Alert severity="error" sx={{ mb: 2 }}>
          {error}
        </Alert>
      )}

      <Grid container spacing={2}>
        <Grid item xs={12} sm={6}>
          <TextField
            fullWidth
            label="银行名称"
            required
            value={product.bank}
            onChange={(e) => handleProductChange('bank', e.target.value)}
          />
        </Grid>
        <Grid item xs={12} sm={6}>
          <TextField
            fullWidth
            label="产品名称"
            required
            value={product.name}
            onChange={(e) => handleProductChange('name', e.target.value)}
          />
        </Grid>
        <Grid item xs={12}>
          <TextField
            fullWidth
            label="单位净值"
            type="number"
            required
            inputProps={{ step: '0.0001', min: '0' }}
            value={product.netWorth}
            onChange={(e) => handleProductChange('netWorth', Number(e.target.value))}
          />
        </Grid>
      </Grid>

      <Box mt={3}>
        <Box display="flex" justifyContent="space-between" alignItems="center" mb={2}>
          <Typography variant="subtitle1">收益率记录</Typography>
          <Button
            variant="outlined"
            size="small"
            onClick={handleAddRate}
          >
            添加产品业绩信息
          </Button>
        </Box>

        {product.historyRates?.map((rate, index) => (
          <Box key={rate.id} mb={2}>
            <Grid container spacing={2} alignItems="center">
              <Grid item xs={12} sm={2}>
                <TextField
                  fullWidth
                  type="date"
                  label="开始日期"
                  required
                  value={formatDateForInput(rate.startDate)}
                  onChange={(e) => handleUpdateRate(index, 'startDate', e.target.value)}
                  InputLabelProps={{ shrink: true }}
                />
              </Grid>
              <Grid item xs={12} sm={2}>
                <TextField
                  fullWidth
                  type="date"
                  label="结束日期"
                  required
                  value={formatDateForInput(rate.endDate)}
                  onChange={(e) => handleUpdateRate(index, 'endDate', e.target.value)}
                  InputLabelProps={{ shrink: true }}
                />
              </Grid>
              <Grid item xs={12} sm={2}>
                <TextField
                  fullWidth
                  type="number"
                  label="宣传年化率(%)"
                  required
                  inputProps={{ step: '0.01', min: '0' }}
                  value={rate.advertisedRate}
                  onChange={(e) => handleUpdateRate(index, 'advertisedRate', e.target.value)}
                />
              </Grid>
              <Grid item xs={12} sm={2}>
                <TextField
                  fullWidth
                  type="number"
                  label="万份收益"
                  required
                  inputProps={{ step: '0.0001', min: '0' }}
                  value={rate.dailyProfit}
                  onChange={(e) => handleUpdateRate(index, 'dailyProfit', e.target.value)}
                />
              </Grid>
              <Grid item xs={12} sm={3}>
                <FormControl fullWidth>
                  <InputLabel>时间标签</InputLabel>
                  <Select
                    value={rate.timeLabel}
                    label="时间标签"
                    onChange={(e) => handleUpdateRate(index, 'timeLabel', e.target.value)}
                  >
                    {Object.values(TimeLabel).map((label) => (
                      <MenuItem key={label} value={label}>
                        {label}
                      </MenuItem>
                    ))}
                  </Select>
                </FormControl>
              </Grid>
              <Grid item xs={12} sm={1}>
                <IconButton
                  color="error"
                  onClick={() => handleRemoveRate(index)}
                >
                  <DeleteIcon />
                </IconButton>
              </Grid>
            </Grid>
          </Box>
        ))}
      </Box>

      <Box mt={3}>
        <Button
          variant="contained"
          color="primary"
          fullWidth
          onClick={handleSubmit}
        >
          保存产品信息
        </Button>
      </Box>
    </Box>
  );
};

export default ProductEntry;